package com.example.blog.controller;

import com.example.blog.dto.SystemSettingDTO;
import com.example.blog.service.SystemSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/settings")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SystemSettingController {
    @Autowired
    private SystemSettingService systemSettingService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<SystemSettingDTO> createSetting(@RequestBody SystemSettingDTO settingDTO) {
        return ResponseEntity.ok(systemSettingService.createSetting(settingDTO));
    }

    @PutMapping("/{key}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<SystemSettingDTO> updateSetting(
            @PathVariable String key,
            @RequestBody SystemSettingDTO settingDTO) {
        return ResponseEntity.ok(systemSettingService.updateSetting(key, settingDTO));
    }

    @DeleteMapping("/{key}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteSetting(@PathVariable String key) {
        systemSettingService.deleteSetting(key);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{key}")
    public ResponseEntity<SystemSettingDTO> getSettingByKey(@PathVariable String key) {
        return ResponseEntity.ok(systemSettingService.getSettingByKey(key));
    }

    @GetMapping("/public")
    public ResponseEntity<List<SystemSettingDTO>> getPublicSettings() {
        return ResponseEntity.ok(systemSettingService.getPublicSettings());
    }

    @GetMapping("/public/map")
    public ResponseEntity<Map<String, String>> getPublicSettingsMap() {
        return ResponseEntity.ok(systemSettingService.getPublicSettingsMap());
    }

    @GetMapping("/category/{category}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Page<SystemSettingDTO>> getSettingsByCategory(
            @PathVariable String category,
            Pageable pageable) {
        return ResponseEntity.ok(systemSettingService.getSettingsByCategory(category, pageable));
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Page<SystemSettingDTO>> getAllSettings(Pageable pageable) {
        return ResponseEntity.ok(systemSettingService.getAllSettings(pageable));
    }

    @PostMapping("/initialize")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> initializeDefaultSettings() {
        systemSettingService.initializeDefaultSettings();
        return ResponseEntity.ok().build();
    }
} 